<template>
  <div class="scheduleview-container" v-loading="loading" @contextmenu="(e)=>e.preventDefault()">
    <div class="appo-header">
      <el-form
        :inline="true"
        :model="appoFormData"
        class="ky-form-inline ky-form-inline-sm">
        <el-form-item>
          <week @weekChange="weekChange" :cur-date.sync="curDate"></week>
        </el-form-item>
        <el-form-item class="item-line-36">
          <el-checkbox v-model="appoFormData.type" @change="appoShowType">仅显示已经发布号源</el-checkbox>
        </el-form-item>
        <!-- <el-form-item>
            <el-button type="text" @click="scheduleChange">{{appoFormData.status==='week'?'切换为月排班':'切换为周排班'}}</el-button>
          </el-form-item> -->
      </el-form>
      <div class="ope_btns" style="text-align: right;" v-permission="['YJYY10001001002', 'YJYY10008002001']">
        <el-button
          size="small"
          v-permission="['YJYY10020380001']"
          v-if="batchUpdateAppoScale && checkRoomObj.CheckRoom && checkRoomInCludeNumberSource(checkRoomObj.CheckRoom)"
          @click="batchNumberPercent"
        >
          批量维护机房号源比例
        </el-button>
        <el-button size="small" :disabled="overdue || appoErrorListData.length>0" @click="appoBatchmove">号源迁移</el-button>
        <el-button size="small" :disabled="overdue || appoErrorListData.length>0" @click="appoCheckNumAdd">批量设置号源数</el-button>
        <el-button size="small" :disabled="overdue|| appoErrorListData.length>0" @click="appoStatusChange">批量修改状态</el-button>
        <el-button size="small" :disabled="overdue|| appoErrorListData.length>0" v-permission="['YJYY10002001']" @click="appoFiltersChange">批量加减限制条件</el-button>
        <el-divider direction="vertical"></el-divider>
        <el-button size="small" :disabled="overdue|| appoErrorListData.length>0" @click="importTemplate">导入模板</el-button>
        <el-button size="small" :disabled="overdue|| appoErrorListData.length>0" @click="importAppoFromPreWeek">导入上周模板</el-button>
        <el-button size="small" icon="el-icon-refresh" :disabled="overdue|| appoErrorListData.length>0" @click="updateTemplate" v-unpermission="['YJYY10008002002']">更新模板</el-button>
        <el-divider direction="vertical"></el-divider>
        <el-button size="small" v-if="checkedAppoData.length>0" @click="openMoreEidt">编辑当日号源</el-button>
        <el-button size="small" type="danger" v-if="appoErrorListData.length>0" @click="appoErrorEidt">出错号源（{{appoErrorListData.length}}）</el-button>
        <el-button size="small" type="danger" v-if="checkedAppoData.length>0 || isCheckedIds.length>0" @click="appoFscDel">删除</el-button>
        <el-button size="small" :disabled="overdue|| appoErrorListData.length>0" @click="scratchSend">保存</el-button>
        <el-button size="small" :disabled="overdue|| appoErrorListData.length>0" type="primary" @click="publishSend">发布</el-button>
      </div>
    </div>
    <fullscheduleTips>
      <div slot="sendTips" v-permission="'YJYY10001001002'">
        <template v-if="appoErrorListData.length>0">请先处理完出错号源，才能进行暂存及发布提交</template>
        <template v-else>请在设置或修改预约机房号源后保存或发布</template>
      </div>
    </fullscheduleTips>
    <div
      class="appo-main"
    >
      <!-- 号源设置界面 -->
      <fullschedule
        ref="fullschedule"
        :overdue="overdue"
        :status-filter.sync="statusFilter"
        :quick-temp-obj="quickTempObj"
        :row-height="84"
        :is-edit="true"
        :is-copy="true"
        :appo-repair="appoRepair"
        :edit-show="true"
        :checkbox-show="true"
        :hospital-code="checkRoomObj.HospitalCode"
        @checkedIdChange="checkedIdChange"
        @addNewSchedule="addNewSchedule"
        @handleAppoInfo="handleAppoInfo"
        @handleAppoDel="handleAppoDel"
        @checkedAllChange="checkedAllChange"
        @appoErrorListChange="appoErrorListChange"
        @openSourceInfoDialog="openSourceInfoDialog"
        @copyInsertChange="copyInsertChange"
        @closeTempDlg="closeTempDlg"
      ></fullschedule>
    </div>
    <!-- <quicktemplate
      :qt-show.sync="qktVisible"
      @quickTempChange="quickTempChange"
    ></quicktemplate> -->
    <!-- 查看预约信息详情 -->
    <appoReleaseInfo
      v-if="isShowAppoReleaseInfo"
      :hospital-code="checkRoomObj.HospitalCode"
      :dep="checkRoomObj.Dep"
      ref="appoReleaseInfo"
      @openSourceInfoDialog="openSourceInfoDialog"
    ></appoReleaseInfo>
    <!-- 模板导入 -->
    <template-fullschedule-dialog
      v-if="isShowTempFScheduleDialog"
      template-type="schedule"
      ref="templatefullscheduledialog"
      :appo-repair="appoRepair"
      @importDataContrast="importDataContrast"
      @closeTempDlg="closeTempDlg"
    ></template-fullschedule-dialog>
    <!-- 修改预约时段状态 -->
    <appoStatusEdit
      v-if="isShowAppoStatusEdit"
      :as-edit-dialog.sync="asEditDialog"
      @appoStatusEidtCb="appoStatusEidtCb"
    >
    </appoStatusEdit>
    <!-- 批量加减号源过滤条件 -->
    <appoFiltersAddSub
      :is-open-dialog.sync="openFiltersDialog"
      :hospital-code="checkRoomObj.HospitalCode"
      :dep="checkRoomObj.Dep"
      @handleBatchAddSubAppoFilters="handleBatchAddSubAppoFilters"
      @closeTempDlg="closeTempDlg"
    ></appoFiltersAddSub>
    <!-- 号源编辑 -->
    <scheduleTemplateForm
      ref="scheduleTemplateForm"
      :is-open-dialog.sync="openTempateFormDialog"
      :temp-title.sync="tempTitle"
      :hospital-code="checkRoomObj.HospitalCode"
      @addScheduleTempSave="addScheduleTempSave"
      @editScheduleTempSave="editScheduleTempSave"
      @openSourceInfoDialog="openSourceInfoDialog"
      @closeTempDlg="closeTempDlg"
    ></scheduleTemplateForm>
    <!-- 追加预约时段号源数 isShowAppoNumEditDlg-->
    <appoNumEditDlg
      v-if="isopenapponumeditdlg"
      :isopenapponumeditdlg.sync="isopenapponumeditdlg"
      :sidebardata="sidebardata"
      @sureEditAppoNumEvent="appoCheckNumAddEidt"></appoNumEditDlg>
    <!-- 时段号源迁移 -->
    <el-dialog
      title="时段号源迁移"
      :visible.sync="appoMoveDialog"
      width="500px"
      :close-on-click-modal="true"
      :destroy-on-close="true"
      top="20%">
      <div>
        <el-form
          class="ky-form-inline ky-form-inline-sm"
          label-position="left"
          label-width="70px">
          <el-form-item label="迁入机房" style="width: 100%;">
            <el-select v-model="appoMoveRoomTarget" disabled clearable style="width: 100%;">
              <el-option
                v-for="(item, index) in roomList"
                :key="index"
                :label="item.label"
                :value="item.label"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="迁出机房" style="width: 100%;">
            <!-- multiple -->
            <el-select v-model="appoMoveRoomInsert" filterable allow-create clearable style="width: 100%;">
              <el-option
                v-for="(item, index) in roomList"
                :key="index"
                :label="item.label"
                :value="item.label"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <div class="flex flex-row justify-between">
          <div>
            <el-tooltip class="item" effect="dark" placement="top-start">
              <div slot="content">
                1、查询【迁出机房】的一周已预约未签到的数据<br/>
                2、过滤符合【迁入机房】的绑定部位数据，不符合的数据不迁移<br/>
                3、【迁出机房】减去已预约数<br/>
                4、【迁入机房】减去号源数，加上已预约数<br/>
                5、已预约数据的时段id和机房改为【迁入机房】
              </div>
              <div class="red">
                注意(请先仔细查看迁移规则):<i class="el-icon-question mar-l-10 red"></i>
              </div>
            </el-tooltip>
          </div>
          <div>
            <el-button size="small" @click="appoMoveDialog = false">取 消</el-button>
            <el-button size="small" type="primary" @click="appoBatchmoveEvent(1)">确 定</el-button>
          </div>
        </div>
      </span>
    </el-dialog>
    <!-- 时段号源复制 -->
    <el-dialog
      title="时段号源复制导入"
      :visible.sync="appoCopyDialog"
      width="500px"
      :close-on-click-modal="true"
      :destroy-on-close="true"
      top="20%">
      <div>
        <el-form
          class="ky-form-inline ky-form-inline-sm"
          label-width="100px">
          <el-form-item label="导入目标星期" style="width: 100%;">
            <el-select v-model="appoCopyWeekInsert" clearable multiple style="width: 100%;">
              <el-option
                v-for="(item, index) in weekOptions"
                :key="index"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="复制目标星期" style="width: 100%;">
            <el-select v-model="appoCopyWeekTarget" clearable style="width: 100%;">
              <el-option
                v-for="(item, index) in weekOptions"
                :key="index"
                :label="item"
                :value="item"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="复制班次" style="width: 100%;">
            <el-select v-model="appoCopySidebar" clearable multiple style="width: 100%;">
              <el-option
                v-for="(item, index) in sidebardata"
                :key="index"
                :label="item.titleLab"
                :value="index"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="appoCopyDialog = false">取 消</el-button>
        <el-button size="small" type="primary" @click="appoCopySend">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 时段号源时间段出错数据 -->
    <appoErrorList ref="appoErrorList" @errorInsert="errorInsert" @errorChange="errorChange"></appoErrorList>
    <!-- 批量修改号源数据 -->
    <approSelectedView v-if="isShowApproSelectedView" ref="selectedViewRef"></approSelectedView>
    <!-- 号源锁定时段信息 -->
    <sourceInfoDialog v-if="isShowSourceInfo" :visible.sync="sourceInfoVisible" :s-data="sData"></sourceInfoDialog>
    <!-- 批量维护号源比例 -->
    <templateRoomFullscheduleDialog1
      v-if="isShowBatchDialog"
      ref="templatefullscheduledialog1"
      :check-room-options="[]"
      :all-checkbox="true"
      :check-room-name="getName(checkRoomObj.CheckRoom)"
      :hospital-code="checkRoomObj.HospitalCode"
      @closeTempDlg="closeTempDlg"
    ></templateRoomFullscheduleDialog1>
  </div>
</template>

<script>
import { setLocalStorage, getLocalStorage } from '@/utils/localStorage'
import bus from '@/api/bus'
import { getHospitalSetting, deleteAppLists } from '@/api/api'
import { setSidebarDataTemp, setSidebarDataEveryDay, getRoomOptions, getRoomTagCurr, setSidebarData } from '@/utils/utils' // this.$utils
import { depSalt, modalityTypeSalt, roomSalt, getAppointmentList, importAppListsbatchupdateSend, postAppTempbatchupdateSend, getBigPartListRoom, appointmentlistdmbBatchmoveSend } from '@/api/room'
import fullschedule from '../components/fullschedule'
import fullscheduleTips from '../components/fullscheduleTips'
import week from '../components/week'
import scheduleTemplateForm from '../components/scheduleTemplateForm'
import appoReleaseInfo from '../components/appoReleaseInfo'
import sourceInfoDialog from '../components/sourceInfoDialog2.vue'
import TemplateFullscheduleDialog from '../components/templateFullscheduleDialog.vue'
import appoFiltersAddSub from '../components/appoFiltersAddSub.vue'
import appoStatusEdit from '../components/appoStatusEdit'
import appoErrorList from '../components/appoErrorList'
import approSelectedView from '../components/approSelectedView'
import appoNumEditDlg from '../components/appoNumEditDlg'
import { dateFormatter } from '@/utils/validate'
import { getWeekStartEndDate, seasonCalCurrDate, flattenDeep } from '@/utils/schedule'
import { Options } from '@/utils/constant'
import templateRoomFullscheduleDialog1 from '../../appointMaintain/rulesSetting/templateFullscheduleDialog'
let parametersTypeByPart1 = 'bigpart'
let parametersTypeByPart2 = 'dengjipart'

export default {
  components: {
    week,
    fullschedule,
    fullscheduleTips,
    scheduleTemplateForm,
    appoReleaseInfo,
    approSelectedView,
    TemplateFullscheduleDialog,
    templateRoomFullscheduleDialog1,
    appoStatusEdit,
    appoFiltersAddSub,
    appoErrorList,
    sourceInfoDialog,
    appoNumEditDlg
  },
  data() {
    return {
      isDev: process.env.NODE_ENV != 'production',
      parametersValuesSplit: this.$store.state.user.parametersValuesSplit,
      isShowScheduleTemplateForm: false,
      isShowAppoReleaseInfo: false,
      isShowTempFScheduleDialog: false,
      isShowAppoStatusEdit: false,
      isShowAppoFiltersAddSub: false,
      isShowAppoErrorList: false,
      isShowApproSelectedView: false,
      isShowSourceInfo: false,
      isShowBatchDialog: false,
      isCheckedIds: [],
      editFlagInLabel: '修改号源数',
      roomList: [],
      appoMoveDialog: false,
      appoMoveRoomTarget: '',
      appoMoveRoomInsert: '',
      parametersTypeByPart: '',
      loading: false,
      appointmentData: [],
      curDate: dateFormatter(new Date()),
      overdue: false, // 判断本周是否全部为过期日期
      tempTitle: '', // 排班新增弹框标题
      checkRomeArr: [], // 查询数据机房联级数组
      appoRepair: this.$store.state.user.appoRepair, // 排班模板判断，是否现在时段间隔的时段占位数据
      // 机房，查询条件数据
      checkRoomObj: {
        HospitalCode: '',
        DepArea: '',
        Dep: '',
        ModalityType: '',
        CheckRoom: '',
        StartDate: '',
        EndDate: '',
        AppointmentStatus: '', // 预约时段状态:暂停预约、节假日、正常预约、设备故障、计划排班；单选
        IsHasFilters: true
      },
      // 排班条件
      appoFormData: {
        month: '',
        week: '',
        day: '',
        type: false,
        status: 'week' // week: 周，month: 月
      },

      // 排班
      step: Number((window.g.DEFAULTSTEPTIME || '00:30').split(':')[1]),
      weekDateFull: [],
      sidebardata: [
        // {
        //   title: '上午班',
        //   start: '8:00',
        //   end: '12:00',
        //   barHeight: 0,
        //   timegather: []
        // }
      ],
      statusFilter: '暂停预约、节假日、正常预约、设备故障、计划排班',
      seasonTxt: '',
      // 快捷选择模板
      quickTempObj: null,
      qktVisible: false,
      // 批量修改预约时段状态
      asEditDialog: false,
      openFiltersDialog: false,
      openTempateFormDialog: false,
      isopenapponumeditdlg: false,
      checkedAppoData: [],
      // 追加预约时段号源数
      checkNumAddDialog: false,
      checkNumEditType: false,
      checkNumAddNum: 5,
      updateField: 'checkNum',
      checkNumSidebarIndex: '',
      // 时段号源，复制
      appoCopyDialog: false,
      // 错误时间时段
      appoErrorListData: [],
      sourceInfoVisible: false, // 时段锁定号源
      sData: {},
      bigpartData: [],
      appoCopyWeekInsert: [],
      appoCopyWeekTarget: '',
      appoCopySidebar: [],
      weekOptions: Options.weekOptions
    }
  },
  computed: {
    appConfig() {
      return this.$store.state.settings.appConfig
    },
    // isBatchAddSub() {
    //   return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isBatchAddSub || false
    // },
    ISUSE_DEFAULTSTEPTIME() {
      return (this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.ISUSE_DEFAULTSTEPTIME) || window.g.ISUSE_DEFAULTSTEPTIME
    },
    isCombineSelectBox() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.isCombineSelectBox
    },
    batchUpdateAppoScale() {
      return this.appConfig && this.appConfig.baseConfig && this.appConfig.baseConfig.batchUpdateAppoScale
    }
  },
  created() {
    // console.log('created=>scheduleView')
    const appoTime = this.$route.query.appoTime
    if (appoTime) {
      this.curDate = dateFormatter(new Date(appoTime))
    }
    bus.$off('editTodaySchedule')
    bus.$on('editTodaySchedule', (data) => {
      // // // console.log('111editTodaySchedule111', data)
      this.openMoreEidt(data)
    })
  },
  mounted() {
    let step = '00:30'
    let appConfig = this.$store.state.settings.appConfig
    if (this.ISUSE_DEFAULTSTEPTIME) {
      step = (appConfig && appConfig.baseConfig && appConfig.baseConfig.DEFAULTSTEPTIME) || '00:30'
    }
    this.step = Number((step).split(':')[1])
  },
  beforeDestroy() {
    // console.log('beforeDestroy=>scheduleView')
    bus.$off('editTodaySchedule')
    // console.log('this.$store.state.user.hospitalCode', this.$store.state.user.hospitalCode)
    // console.log('roomCascaderHospCode', getLocalStorage('roomCascaderHospCode'))
    if (this.$store.state.user.hospitalCode != getLocalStorage('roomCascaderHospCode')) {
      setLocalStorage('yjyy-roomKeyToDeptRoom', JSON.stringify({}))
    }
  },
  methods: {
    getName(checkroom) {
      checkroom = checkroom || ''
      return checkroom.split('$#')[0]
    },
    checkRoomInCludeNumberSource(checkroom) {
      if (!window.g.isEnableNumberRuleRoom) return true
      checkroom = checkroom || ''
      let checkroomName = checkroom.split('$#')[0]
      return (window.g.isEnableNumberRuleRoom || []).includes(checkroomName)
    },
    batchNumberPercent(checkroom) {
      this.isShowBatchDialog = true
      checkroom = checkroom || ''
      this.$nextTick(() => {
        this.$refs.templatefullscheduledialog1.init([], dateFormatter(new Date()))
      })
    },
    // 复制 提交
    async appoCopySend() {
      // console.log('appoCopySend')
      if (!this.appoCopyWeekTarget) {
        this.$message.warning('请选择复制目标星期！')
        return false
      } else if (this.appoCopyWeekInsert.length === 0) {
        this.$message.warning('请选择导入目标星期！')
        return false
      }

      /**
       * 1、获取复制目标星期的数据（判断是否选择班次，如果没有整天复制导入）。
       * 2、把获取到的目标数据id 设为 0
       * 3、获取导入目标星期的数据
       */

      const _scheduledata = JSON.parse(JSON.stringify(this.$refs.fullschedule.scheduledata))
      // console.log('_scheduledata', _scheduledata)
      // 获取复制目标星期的数据
      let copyTargetSchedule = _scheduledata.find(item => item.week === this.appoCopyWeekTarget)
      copyTargetSchedule = JSON.parse(JSON.stringify(copyTargetSchedule))
      // console.log('copyTargetSchedule', copyTargetSchedule)
      let tAppo = [] // 所要被复制的号源
      // console.log('this.appoCopySidebar', this.appoCopySidebar)
      if (this.appoCopySidebar.length === 0) { // 复制班次
        tAppo = copyTargetSchedule.appointment.map(ia => ia.filter(a => !a.isAddBox))
      } else {
        let copyTargetAppointment = copyTargetSchedule.appointment.map(ia => ia.filter(a => !a.isAddBox))
        // // console.log('copyTargetAppointment', JSON.stringify(copyTargetAppointment))
        copyTargetAppointment.forEach((appos, index) => {
          // // console.log('index', index)
          // 把上午班或下午班加到tAppo数组里
          if (this.appoCopySidebar.indexOf(index) >= 0) {
            tAppo.push(appos)
          } else {
            tAppo.push([])
          }
        })
      }
      // 把复制的数据id设置为0 tAppo=[[上午班数组],[下午班数组]]
      tAppo.forEach(appos => {
        // // console.log('appos瞅瞅', appos)
        if (appos.length > 0) {
          appos.forEach(item => {
            item.id = 0
            item.callNum = 0 // 已预约数量不要复制过去，所以设置为0
          })
        }
      })
      // // // console.log('tAppo === ', tAppo)
      let tAppoFlat = flattenDeep(tAppo)
      if (tAppoFlat.length === 0) {
        this.$message.warning('选择的复制目标星期无时段号源数据！')
        return false
      }
      let insertAppoArr = [] // 需要导入的数据数组，[每一周的号源数据数组]
      _scheduledata.forEach(sche => {
        // // // console.log(this.appoCopyWeekInsert.includes(sche.week))
        if (this.appoCopyWeekInsert.includes(sche.week)) {
          // 把复制数据星期几设置为导入星期几
          tAppo.forEach(appos => {
            if (appos.length > 0) {
              appos.forEach(item => {
                item.week = sche.week
              })
            }
          })
          if (this.appoCopySidebar.length === 0) {
            sche.appointment = JSON.parse(JSON.stringify(tAppo))
          } else {
            this.appoCopySidebar.forEach(sideIndex => {
              sche.appointment[sideIndex] = JSON.parse(JSON.stringify(tAppo[sideIndex]))
            })
          }
          // console.log('sche.appointment', sche.appointment)
          insertAppoArr.push(flattenDeep(sche.appointment))
        }
      })
      // console.log('copy insertAppoArr === ', insertAppoArr)
      await this.$refs.fullschedule.appoImport(insertAppoArr)
      this.appoCopyDialog = false
    },
    // 复制导入选择弹框
    copyInsertChange(data) {
      this.appoCopyDialog = true
      const { index } = data
      // this.appoCopyWeekInsert = [this.weekOptions[index]]
      this.appoCopyWeekTarget = this.weekOptions[index]
    },
    appoBatchmove() {
      // 号源迁移
      this.roomList = getRoomOptions()
      this.appoMoveRoomTarget = getRoomTagCurr().split('$')[0]
      this.appoMoveDialog = true
    },
    appoBatchmoveEvent(type) {
      // 号源迁移事件
      let params = {
        hospitalCode: this.checkRoomObj.HospitalCode, // 医院编号
        depArea: this.checkRoomObj.DepArea, // 影像区域
        dep: this.checkRoomObj.Dep, // 检查部门
        modalityType: this.checkRoomObj.ModalityType, // 设备类型
        // modality: '', // 检查设备
        checkRoom: this.checkRoomObj.CheckRoom, // 检查机房
        // checkGroup: '', // 非必填 检查分组
        batchType: type || 1, // 功能类型(1暂存、2发布)
        appointmentDate: this.checkRoomObj.StartDate, // 检查日期 为了删除所有时段断日期用
        moveCheckRoom: this.appoMoveRoomInsert // 被迁移机房名称
      }
      // // console.log('params', params)
      this.loading = true
      appointmentlistdmbBatchmoveSend(params).then(res => {
        this.loading = false
        if (res && res.code === 10000) {
          this.$message.success(`${res.message}`)
          this.appoMoveDialog = false
          this.getAppoList()
        }
      })
    },
    getBigPart() {
      return new Promise(async resolve => {
        const params = {
          HospitalCode: this.checkRoomObj.HospitalCode,
          Dep: this.checkRoomObj.Dep
        }
        // // // console.log('params', params)
        await getBigPartListRoom(params).then(res => {
          if (res && res.code === 10000) {
            this.bigpartData = res.content.list
            // // // console.log('getBigPartListRoom_res.content.list', res.content.list)
            // setLocalStorage('BIGPARTLIST', JSON.stringify(this.bigpartData))
          }
        })
        resolve()
      })
    },
    openSourceInfoDialog(val) {
      // 打开号源锁定时段信息
      this.isShowSourceInfo = true
      this.$nextTick(() => {
        this.sourceInfoVisible = true
        this.sData = val
      })
    },
    // 发布
    async publishSend() {
      if (this.appoErrorListData.length > 0) {
        this.$message.warning('预约号源时段错误的数据须先处理完！')
        return
      }
      this.$confirm('保存当前页面所有时段号源数据，并发布计划排班号源, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.batchSend(2)
      }).catch(() => {})
    },
    // 暂存
    async scratchSend() {
      const _isChanged = this.$refs.fullschedule.isChanged
      if (this.appoErrorListData.length > 0) {
        this.$message.warning('预约号源时段错误的数据须先处理完！')
        return
      } else if (!_isChanged) {
        this.$message.info('提示：机房号源未修改！')
        return
      }
      this.$confirm('保存当前页面所有时段号源数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.batchSend(1)
      }).catch(() => {})
    },
    batchSend(type) {
      let params = {
        'hospitalCode': this.checkRoomObj.HospitalCode,
        'depArea': this.checkRoomObj.DepArea,
        'dep': this.checkRoomObj.Dep,
        'modalityType': this.checkRoomObj.ModalityType,
        'checkRoom': this.checkRoomObj.CheckRoom,
        'appointmentDate': this.checkRoomObj.StartDate,
        'batchType': type || 1, // 1暂存、2发布
        'batchUpdateAppointmentListDmbs': []
      }
      // 获取排班组件内的 排班数据
      let scedulingData = this.$refs.fullschedule.scheduledata
      // 这里数据正常
      let _scheduledata = JSON.parse(JSON.stringify(scedulingData))
      // // console.log('_scheduledata', _scheduledata)
      _scheduledata.forEach(sched => {
        sched.appointment.forEach((appos, index) => {
          // // // console.log('appos', appos)
          appos.forEach(appo => {
            // // // console.log('appo', appo)
            // // // console.log('appo.isBad', appo.isBad)
            // 20231103新增
            // if (appo.isBad) {
            //   isBad = true
            // }
            if (!appo.isAddBox) {
              appo.addNum = appo.addNum * 1
              appo.checkNum = appo.checkNum * 1
              appo.initialNum = appo.initialNum * 1
              appo.reserveNum = appo.reserveNum * 1
              appo.callNum = appo.callNum ? appo.callNum * 1 : 0
              // // // console.log('appointmentFilters==>1231231321', appo.appointmentFilters)
              // // // console.log('appo.appointmentFilters', JSON.stringify(appo.appointmentFilters))
              // // // console.log('appo.appointmentFilters.length', appo.appointmentFilters.length)
              if (appo.appointmentFilters.length > 0) {
                for (let i = 0; i < appo.appointmentFilters.length; i++) {
                  // // // console.log('待查看this.$store.state.user.parametersTypeByPartKey2', this.$store.state.user.parametersTypeByPartKey2)
                  if (appo.appointmentFilters[i].parametersType.toLowerCase() === 'dengjipart' && this.$store.state.user.parametersTypeByPartKey2.toLowerCase() == 'dengjipart' && this.parametersTypeByPart.toLowerCase() == 'bigpart') {
                    appo.appointmentFilters[i].parametersName = '检查项目' // 检查项目
                  }
                  if (appo.appointmentFilters[i].parametersType.toLowerCase() === 'dengjipart' && this.parametersTypeByPart.toLowerCase() == 'dengjipart') {
                    appo.appointmentFilters[i].parametersName = '检查部位' // 检查项目
                  }
                  if (appo.appointmentFilters[i].parametersType === 'pat_type') {
                    appo.appointmentFilters[i].parametersName = '患者类型'
                  } else if (appo.appointmentFilters[i].parametersType === 'LCYY') {
                    appo.appointmentFilters[i].parametersName = '临床预约'
                  } else if (appo.appointmentFilters[i].parametersType === 'WYYY') {
                    appo.appointmentFilters[i].parametersName = '外院预约'
                  } else if (appo.appointmentFilters[i].parametersType === 'CheckType') {
                    appo.appointmentFilters[i].parametersName = '检查方法'
                  } else if (appo.appointmentFilters[i].parametersType === 'VIP') {
                    appo.appointmentFilters[i].parametersName = '转诊预约'
                  } else if (appo.appointmentFilters[i].parametersType === 'YYLY') {
                    appo.appointmentFilters[i].parametersName = '预约来源'
                  } else if (appo.appointmentFilters[i].parametersType === 'sex') {
                    appo.appointmentFilters[i].parametersName = '患者性别'
                  } else if (appo.appointmentFilters[i].parametersType === 'AgeEnd') {
                    appo.appointmentFilters[i].parametersName = '最大年龄'
                  } else if (appo.appointmentFilters[i].parametersType === 'AgeBegin') {
                    appo.appointmentFilters[i].parametersName = '最小年龄'
                  }
                }
                // // // console.log('上半场', appo.appointmentFilters)
                // 提前过滤掉appointmentFilters中parametersValues值为空的item
                let len = appo.appointmentFilters.length
                while (len > 0) {
                  if (appo.appointmentFilters[len - 1].parametersValues == '') {
                    appo.appointmentFilters.splice(len - 1, 1)
                  }
                  len -= 1
                }
              } else {
                // 优化初始数据
                if (this.isCombineSelectBox) {
                  let _appoFlrObj = {
                    parametersName: '外院预约',
                    parametersType: 'WYYY',
                    parametersValues: '非互联网预约'
                  }
                  appo.appointmentFilters.push(_appoFlrObj)
                  _appoFlrObj = {
                    parametersName: '临床预约',
                    parametersType: 'LCYY',
                    parametersValues: '非临床预约'
                  }
                  appo.appointmentFilters.push(_appoFlrObj)
                  _appoFlrObj = {
                    parametersName: '转诊预约',
                    parametersType: 'VIP',
                    parametersValues: '非转诊预约'
                  }
                  appo.appointmentFilters.push(_appoFlrObj)
                }
              }
              // appo循环
              let arr = []
              let obj = []
              for (let i = 0; i < appo.appointmentFilters.length; i++) {
                if (!obj.some(item => item.parametersType === appo.appointmentFilters[i].parametersType)) {
                  obj.push(appo.appointmentFilters[i])
                  arr.push({
                    gname: appo.appointmentFilters[i].parametersType,
                    data: [appo.appointmentFilters[i]]
                  })
                } else {
                  for (let k = 0; k < arr.length; k++) {
                    if (arr[k].gname === appo.appointmentFilters[i].parametersType) {
                      arr[k].data.push(appo.appointmentFilters[i])
                    }
                  }
                }
              }
              let arr2 = []
              arr.forEach(item => {
                console.log('==========join=============')
                arr2.push({
                  parametersName: item.data[0].parametersName,
                  parametersType: item.data[0].parametersType,
                  parametersValues: item.data.map(item => item.parametersValues).join(this.parametersValuesSplit) // 咦这里怎么用逗号的，不应该是中文‘、’号吗，需要排查什么情况下会执行到这里
                })
              })
              appo.appointmentFilters = arr2
              // debugger
              appo.appointmentStatus = appo.appointmentStatus || '计划排班'
              params.batchUpdateAppointmentListDmbs.push(appo)
            }
          })
        })
      })
      // // // console.log('importAppListsbatchupdateSend')
      // 目前无需判断时间的正确性，所以直接保存号源
      this.loading = true
      importAppListsbatchupdateSend(params).then(res => {
        this.loading = false
        if (res && res.code === 10000) {
          this.$message.success(`${res.message}`)
          this.getAppoList()
        }
      })
      // 若智能判断时间是否超出时令之外，则启用下面代码
      // if (isBad) {
      //   this.$message.warning('预约号源时段错误的数据须先处理完！')
      // } else {
      //   this.loading = true
      //   importAppListsbatchupdateSend(params).then(res => {
      //     this.loading = false
      //     if (res && res.code === 10000) {
      //       this.$message.success(`${res.message}`)
      //       this.getAppoList()
      //     }
      //   })
      // }
    },
    getParameterDep(data) {
      // // // console.log('getParameterDep')
      let dep = data.length > 0 ? data[2] : ''
      let _dep = ''
      if (dep) { // this.dep=>1 SALT-DEP-CT
        _dep = dep.replace(depSalt, '') // depSalt = 'SALT-DEP-'
      }
      // _dep = CT
      this.parametersTypeByPart = parametersTypeByPart1
      const _deps = this.$store.state.user.depSettings
      // // // console.log('_deps', JSON.stringify(_deps))
      // _deps
      // [{"dep":"CT","parametersTypeByPart":"dengjipart"},{"dep":"MRI","parametersTypeByPart":"bigpart"},{"dep":"XRAY","parametersTypeByPart":"bigpart"}]
      if (_dep && _deps && _deps.length > 0) {
        _deps.forEach(item => {
          if (item.parametersTypeByPart === parametersTypeByPart2 && item.dep === _dep) {
            this.parametersTypeByPart = parametersTypeByPart2 // 'BIGPART' // parametersTypeByPart2
            setLocalStorage('parametersTypeByPart', this.parametersTypeByPart)
            // // // console.log('this.parametersTypeByPart==result==', this.parametersTypeByPart) // BIGPART
            // 当this.parametersTypeByPart == dengjipart 将大部位值替换成dengjipart且不判断小部位
          }
        })
      }
      // // // // console.log('_dep_dep_dep_dep', _dep)
      // // // // console.log('parametersTypeByPart', this.parametersTypeByPart)
    },
    async init(data) {
      // 【'47000593033030211A1001', '龙湾院区', 'SALT-DEP-CT', 'SALT-MTYPE-CT', '龙湾-测试CT2$#CT'】
      // // // console.log('==isRoom?', data)
      this.getParameterDep(data)
      if (JSON.stringify(this.checkRomeArr) === JSON.stringify(data)) return false
      if (data && data.length > 0) {
        this.dlgClose()
        this.checkRomeArr = [...data]
        this.checkRoomObj.HospitalCode = data[0]
        this.checkRoomObj.DepArea = data[1]
        this.checkRoomObj.Dep = data[2]
        this.checkRoomObj.ModalityType = data[3]
        this.checkRoomObj.CheckRoom = data[4]
        this.checkRoomObj.AppointmentStatus = ''
        this.appoErrorListData = []
        this.loading = true
        await this.getWeekDateTimeFull()
        console.log('await this.getAppoTimeTemp()')
        await this.getAppoTimeTemp()
        // 获取预约排班数据
        // // console.log('let me see see:', this.checkRoomObj)
        const appodata = await getAppointmentList(this.checkRoomObj)
        // // console.log('获取预约排班数据appodata', appodata)
        await this.$refs.fullschedule.init({ date: this.curDate, sidebardata: this.sidebardata, seasonTxt: this.seasonTxt })
        this.loading = false
        // this.$refs.scheduleTemplateForm.getTempList(data)
        this.getAppoList(appodata)
        await this.getBigPart()
      }
    },
    // 刷新当前模板
    async refresh() {
      this.loading = true
      const appodata = await getAppointmentList(this.checkRoomObj)
      await this.$refs.fullschedule.init({ date: this.curDate, sidebardata: this.sidebardata, seasonTxt: this.seasonTxt })
      // this.$refs.scheduleTemplateForm.getTempList(data)
      this.getAppoList(appodata)
      this.loading = false
    },
    // 获取排班一周的完整时间数组
    getWeekDateTimeFull() {
      return new Promise(async resolve => {
        this.weekDateFull = await getWeekStartEndDate(this.curDate)
        this.overdue = false
        if (this.weekDateFull.length > 0) {
          this.checkRoomObj.StartDate = this.weekDateFull[0]
          this.checkRoomObj.EndDate = this.weekDateFull[this.weekDateFull.length - 1]
          const endTime = dateFormatter(new Date(this.checkRoomObj.EndDate).getTime(), false) + ' 23:59:59'
          // // // console.log('endTime', endTime)
          if (new Date().getTime() > new Date(endTime).getTime()) {
            this.overdue = true
            // // console.log('是否过期', this.overdue)
          }
        }
        resolve()
      })
    },
    // 查询，获取排班数据
    async getAppoList(appodata) {
      this.loading = true
      const _appodata = appodata || await getAppointmentList(this.checkRoomObj)
      this.loading = false
      // console.log('查询，获取排班数据_appodata', _appodata)
      this.$refs.fullschedule.appoPull(_appodata, null, true, false)
    },
    // 当前排班类型切换
    scheduleChange() {
      this.appoFormData.status = this.appoFormData.status === 'week' ? 'month' : 'week'
    },
    // 周-变化
    async weekChange() {
      // // // console.log('weekChange')
      this.loading = true
      this.appoErrorListData = []
      // 计算查询的周起始,结束时间
      await this.getWeekDateTimeFull()
      // 计算时令时段
      await this.getAppoTimeTemp()
      // 获取预约排班数据
      const appodata = await getAppointmentList(this.checkRoomObj)
      // // // console.log('weekChange=>appodata', appodata)
      // 初始预约排班
      await this.$refs.fullschedule.init({ date: this.curDate, sidebardata: this.sidebardata, seasonTxt: this.seasonTxt })
      this.loading = false
      // 加载数据
      this.getAppoList(appodata)
    },
    // 快捷模板选择监听
    quickTempChange(quickTempObj) {
      this.quickTempObj = quickTempObj ? { ...quickTempObj } : null
    },

    // 导入模板
    importTemplate() {
      this.isShowTempFScheduleDialog = true
      this.$nextTick(() => {
        this.$refs.templatefullscheduledialog.init(this.checkRomeArr, this.curDate)
      })
    },
    closeTempDlg() {
      console.log('closeTempDlg')
      this.isShowTempFScheduleDialog = false
      this.isShowBatchDialog = false
      this.isShowScheduleTemplateForm = false
      this.isShowAppoFiltersAddSub = false
      this.openFiltersDialog = false
      this.openTempateFormDialog = false
    },
    // 新增排班模板
    addNewSchedule(data) {
      console.log('addNewSchedule')
      this.isShowScheduleTemplateForm = true
      this.openTempateFormDialog = true
      // // // console.log('addNewSchedule:====', data)
      const bTime = data.timeSel.split('-')[0]
      const eTime = '24:00'// data.timeSel.split('-')[1]
      const minMaxNum = this.$refs.fullschedule.getInitialMinMaxNum(bTime, eTime)
      this.tempTitle = '新增机房号源'
      const stfData = {
        time: data.time,
        startNum: data.startNum,
        appoInfo: null,
        step: this.step,
        room: this.checkRomeArr,
        timeSel: data.timeSel,
        minMaxNum
      }
      this.isShowAppoReleaseInfo && this.$refs.appoReleaseInfo.close()
      // // // console.log('addNewSchedule==stfData==data_from_addNewSchedule', stfData)
      this.$nextTick(() => {
        this.$refs.scheduleTemplateForm.init(stfData)
      })
    },
    addScheduleTempSave(data) {
      // // // console.log('进入addScheduleTempSave——打印data是否正常？', data)
      // // // console.log('预进入addNew')
      this.$refs.fullschedule.addNew(data)
    },
    // 查看、编辑预约排班信息
    handleAppoInfo(data) {
      if (!data.disableDate) {
        this.openTempateFormDialog = true
        this.isShowAppoReleaseInfo = false
      }
      this.isCheckedIds = data.isCheckedIds
      console.log('查看、编辑预约排班信息_handleAppoInfo', data)
      const bTime = data.appoInfo.beginTime
      const eTime = '24:00'// data.appoInfo.endTime
      const minMaxNum = this.$refs.fullschedule.getInitialMinMaxNum(bTime, eTime)
      // // // console.log(data.appoInfo.checkClass)
      this.tempTitle = '编辑机房号源'
      // disableDate 判断时间是否已经为过去时间，今天之前
      // data.appoInfo.appointmentStatus === '正常预约' ||
      if (data.disableDate) {
        this.isShowScheduleTemplateForm && this.$refs.scheduleTemplateForm.close()
        this.isShowAppoReleaseInfo = true
        this.$nextTick(() => {
          this.$refs.appoReleaseInfo.init(data.appoInfo)
        })
      } else {
        let b = false
        if (data.isCheckedIds.length > 0) {
          b = true
        }
        const stfData = {
          time: data.time,
          appoInfo: data.appoInfo,
          room: this.checkRomeArr,
          step: this.step,
          timeSel: data.timeSel,
          minMaxNum,
          checkMore: b
        }
        this.appoReleaseInfo && this.$refs.appoReleaseInfo.close()
        this.isShowScheduleTemplateForm = true
        setTimeout(() => {
          console.log('stfData', stfData)
          this.$refs.scheduleTemplateForm.init(stfData)
        }, 200)
      }
    },
    handleBatchAddSubAppoFilters(ruleParams) {
      console.log('handleBatchAddSubAppoFilters')
      this.$refs.fullschedule.batchAddSubAppoFilters(ruleParams)
    },
    editScheduleTempSave(data) {
      this.$refs.fullschedule.editUpdate(data)
    },
    // 批量修改预约时段状态
    appoStatusChange() {
      this.isShowAppoStatusEdit = true
      // // console.log('this.isCheckedIds.length', this.isCheckedIds.length)
      if (this.isCheckedIds.length === 0) {
        this.$message.warning('请先勾选号源！')
        return
      }
      this.$nextTick(() => {
        this.asEditDialog = true
      })
    },
    appoStatusEidtCb(status) {
      this.asEditDialog = false
      this.$refs.fullschedule.resetAppoStatus(status)
    },
    // 批量加减过滤条件
    appoFiltersChange() {
      this.isShowAppoFiltersAddSub = true
      // // console.log('this.isCheckedIds.length', this.isCheckedIds.length)
      if (this.isCheckedIds.length === 0) {
        this.$message.warning('请先勾选号源！')
        return
      }
      // this.dep = this.checkRomeArr.Dep
      // console.log('this.dep', this.dep)
      this.$nextTick(() => {
        this.openFiltersDialog = true
      })
    },
    // 批量设置号源数
    appoCheckNumAdd() {
      if (this.isCheckedIds.length === 0) {
        this.$message.warning('请先勾选号源！')
      } else {
        // this.checkNumAddDialog = true
        this.isopenapponumeditdlg = true
      }
    },
    async appoCheckNumAddEidt(res) {
      // console.log('appoCheckNumAddEidt=>res', res)
      if (!res.checkNumAddNum) {
        this.$message.warning('数量不能为空！')
        return
      } else if (res.checkNumAddNum < 0) {
        this.$message.warning('数量不能小于0！')
        return
      }
      await this.$refs.fullschedule.setDateNumUpdate(res.checkNumAddNum, res.checkNumSidebarIndex, res.checkNumEditType, res.updateField)
      // this.checkNumAddDialog = false
      this.isopenapponumeditdlg = false
    },
    appoFscDel() {
      this.$refs.fullschedule.appoDelDay()
    },
    checkedIdChange(data) {
      this.isCheckedIds = data
    },
    // 监听排班组件日全选事件
    checkedAllChange() {
      // console.log('checkedAllChange=>触发事件监听')
      let scheduledata = []
      const schedule = JSON.parse(JSON.stringify(this.$refs.fullschedule.scheduledata))
      // console.log('schedule', schedule)
      schedule.forEach(item => {
        if (item.checkedAll) {
          scheduledata.push(item)
        }
      })
      this.checkedAppoData = scheduledata
    },

    // 显示条件改变
    appoShowType(val) {
      // // // console.log(val)
      this.statusFilter = !val ? '暂停预约、节假日、正常预约、设备故障、计划排班' : '正常预约'
    },
    // 获取时段数据,计算时段
    async getAppoTimeTemp() {
      return new Promise(async resolve => {
        const depArr = (this.checkRoomObj.Dep && this.checkRoomObj.Dep.indexOf('-') > -1 && this.checkRoomObj.Dep.split('-')) || ''
        let dep = (depArr && depArr.length && depArr[depArr.length - 1]) || ''
        if (this.checkRoomObj.Dep && this.checkRoomObj.Dep.indexOf('-') == -1) {
          dep = this.checkRoomObj.Dep
        }
        const param = {
          HospitalCode: this.checkRoomObj.HospitalCode,
          depArea: this.checkRoomObj.DepArea,
          dep
        }
        await getHospitalSetting(param).then(async res => {
          if (res && res.code === 10000) {
            const seasonSettings = res.content.seasonSettings
            const season = seasonCalCurrDate(seasonSettings, this.weekDateFull[0], true, false, true)
            // console.log('getAppoTimeTemp=>season', season)
            this.seasonTxt = season.title
            this.sidebardata = season.sidebardata
            setSidebarData(JSON.stringify(this.sidebardata))
            // 获取模板的时间轴
            const seasonTemp = seasonCalCurrDate(seasonSettings, this.weekDateFull[0], true, false, true)
            setSidebarDataTemp(JSON.stringify(seasonTemp.sidebardata))
            // 设置每天的时间轴
            let everyDaySiderBarData = {}
            this.weekDateFull.forEach(item => {
              // console.log('weekDateFull', item)
              let s = seasonCalCurrDate(seasonSettings, item, true)
              // console.log('根据时令计算出时间轴的数据s', JSON.parse(JSON.stringify(s)))
              everyDaySiderBarData[item] = s.sidebardata
            })
            // // console.log('getHospitalSetting=>setSidebarDataEveryDay', everyDaySiderBarData)
            setSidebarDataEveryDay(JSON.stringify(everyDaySiderBarData))
          }
        })
        resolve()
      })
    },
    // 删除排班时段数据
    handleAppoDel(appoInfo) {
      // // console.log(appoInfo)
      const params = {
        HospitalCode: this.checkRoomObj.HospitalCode,
        Id: appoInfo.id
      }
      this.$confirm('删除预约时段数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        deleteAppLists(params).then(res => {
          this.loading = false
          if (res && res.code === 10000) {
            // bus.$emit('delAppoSuccess')
            this.$refs.fullschedule.appoDelSuccessCb()
          }
        })
      }).catch(() => {})
    },
    // 导入数据对比判断、抛出提示
    async importDataContrast(scheData) {
      console.log('importDataContrast=>scheData', scheData)
      // 暂停预约、节假日、正常预约、设备故障、计划排班
      // 1、对导入数据、原有数据(appointment)进行平铺处理 [[],[]] > [{},{}]
      // 2、平铺处理的导入数据，初始化处理，医院、科室、状态等
      // 3、原有数据，与导入数据的同日期对比，计算存在时段时间区间交集的数据个数、及交集的数据且状态为 正常预约 的数据个数
      // 4、根据计算出来的交集数据个数、交集且状态为 ‘正常预约’ 的数据个数，做出提示

      // 获取排班组件内的 排班数据
      const { importScheduleData, isWeek } = scheData
      const _scheduledata = JSON.parse(JSON.stringify(this.$refs.fullschedule.scheduledata))
      const IScheData = importScheduleData
      let roomObj = JSON.parse(JSON.stringify(this.checkRoomObj))
      let _scheAppoData = [] // 存放
      let _importScheAppoData = []
      IScheData.forEach(iSche => {
        const iScheWeek = iSche.week
        // 获取当前日期是否可以编辑
        const _weekIndex = _scheduledata.findIndex(sched => sched.week === iScheWeek)
        const _disable = _weekIndex >= 0 ? _scheduledata[_weekIndex].disable : false
        if (_disable) {
          // 判断当前日期是否为今天之前的日期，今天日期之前的时间不可以修改预约时段
          return
        }
        let iScheAppoArr = iSche.appointment
        iScheAppoArr = flattenDeep(iScheAppoArr)
        // 初始化时段数据
        iScheAppoArr.forEach(iScheAppo => {
          iScheAppo.hospitalCode = roomObj.HospitalCode
          iScheAppo.depArea = roomObj.DepArea
          iScheAppo.dep = roomObj.Dep.indexOf(depSalt) >= 0 ? roomObj.Dep.replace(depSalt, '') : roomObj.Dep
          iScheAppo.modalityType = roomObj.ModalityType.indexOf(modalityTypeSalt) >= 0 ? roomObj.ModalityType.replace(modalityTypeSalt, '') : roomObj.ModalityType
          iScheAppo.checkRoom = roomObj.CheckRoom.indexOf(roomSalt) >= 0 ? roomObj.CheckRoom.replace(roomSalt, '') : roomObj.CheckRoom
          iScheAppo.appointmentStatus = ''
          iScheAppo.remark2 = iScheAppo.recordCode
          iScheAppo.id = 0
        })
        // // console.log(iScheAppoArr)
        _importScheAppoData.push(flattenDeep(iScheAppoArr))
        _scheduledata.forEach(sche => {
          if (sche.week === iScheWeek) {
            // 相同的星期
            // const appoString = JSON.stringify(sche.appointment)
            let scheAppoArr = sche.appointment.map(appos => appos.filter(ap => !ap.isAddBox))
            _scheAppoData.push(flattenDeep(scheAppoArr))
          }
        })
      })
      let lapAppo = 0
      let publishAppo = 0
      if (_scheAppoData.length === 0) {
        // 预约排班视图界面当前选择的模板时间没有数据
      } else {
        const ISLen = _importScheAppoData.length
        for (let i = 0; i < ISLen; i++) {
          const ISDayAppos = _importScheAppoData[i]
          const ISDLen = ISDayAppos.length
          for (let j = 0; j < ISDLen; j++) {
            const ISDAppo = ISDayAppos[j]
            let IminTime = ISDAppo.beginTime
            let ImaxTime = ISDAppo.endTime
            let ImaxMin = ImaxTime.split(':')[0] * 60 + ImaxTime.split(':')[1] * 1
            let IminMin = IminTime.split(':')[0] * 60 + IminTime.split(':')[1] * 1
            _scheAppoData[i].forEach(appo => {
              let minTime = appo.beginTime
              let maxTime = appo.endTime
              let maxMin = maxTime.split(':')[0] * 60 + maxTime.split(':')[1] * 1
              let minMin = minTime.split(':')[0] * 60 + minTime.split(':')[1] * 1
              // 判断时段区间的交集情况
              if (!(ImaxMin <= minMin && IminMin < minMin) && !(ImaxMin > maxMin && IminMin >= maxMin)) {
                lapAppo++
                if (appo.appointmentStatus === '正常预约') {
                  publishAppo++
                }
              }
            })
          }
        }
      }
      if (publishAppo > 0) {
        this.$message.warning('导入号源时段存在已发布号源，禁止导入！')
        return false
      }
      if (lapAppo > 0) {
        this.$confirm('导入号源时段区间已存在号源，是否覆盖？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          await this.$refs.fullschedule.appoImport(_importScheAppoData, isWeek)
          this.isShowTempFScheduleDialog && this.$refs.templatefullscheduledialog.closeTempDlg()
        }).catch(() => {})
        return false
      }
      console.log('_importScheAppoData', _importScheAppoData)
      await this.$refs.fullschedule.appoImport(_importScheAppoData, isWeek)
      this.isShowTempFScheduleDialog && this.$refs.templatefullscheduledialog.closeTempDlg()
    },
    // 导入上周模板
    async importAppoFromPreWeek() {
      // 获取上周数据
      let _appoData = []
      const _scheduledata = JSON.parse(JSON.stringify(this.$refs.fullschedule.scheduledata))
      _scheduledata.forEach(sched => {
        _appoData = _appoData.concat(flattenDeep(sched.appointment))
      })
      // 判断当前时段数据是否存在已发布数据
      for (let appoIndex in _appoData) {
        if (_appoData[appoIndex].appointmentStatus === '正常预约') {
          this.$message.warning('当前导入时段与存在已发布的预约时段冲突！')
          return
        }
      }

      const preAppodata = await this.getAppoPreWeek()
      if (preAppodata.length > 0) {
        preAppodata.forEach(appo => {
          appo.appointmentDate = dateFormatter(new Date(appo.appointmentDate).getTime() + 7 * 24 * 60 * 60 * 1000, false)
          appo.appointmentStatus = ''
          appo.id = 0
          if (appo.callNum > 0) {
            // 导入上周时段数据，需要把已预约数据加到号源数上，已预约数清0
            appo.checkNum = appo.checkNum + appo.callNum
            appo.callNum = 0
          }
        })
        const _preAppodata = preAppodata.filter(appo => {
          const dTime = new Date(appo.appointmentDate).getTime()
          const cIndex = _scheduledata.findIndex(item => new Date(item.dateFull).getTime() === dTime)
          return cIndex >= 0 && !_scheduledata[cIndex].disable
        })
        // // // console.log(_preAppodata)
        if (_preAppodata.length === 0) {
          this.$message.info('自动过滤今天之前的时段预约，暂无时段可添加！')
        } else {
          this.$confirm('确认导入上周号源时段模板？(自动过滤今天之前的时段)', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            this.$refs.fullschedule.appoPull(_preAppodata, true)
            // this.$refs.fullschedule.appoImport(_preAppodata, true)
          }).catch(() => {})
        }
      } else {
        this.$message.warning('上周未设置机房号源！')
      }
    },
    // 获取上周模板数据
    getAppoPreWeek() {
      return new Promise(async resolve => {
        const params = { ...this.checkRoomObj }
        const preWeekDate = await getWeekStartEndDate(dateFormatter(new Date(this.curDate).getTime() - 7 * 24 * 60 * 60 * 1000))
        params.StartDate = preWeekDate[0]
        params.EndDate = preWeekDate[preWeekDate.length - 1]

        const appodata = await getAppointmentList(params)
        resolve(appodata)
      })
    },
    // 更新到排班模板
    updateTemplate() {
      let params = {
        'hospitalCode': this.checkRoomObj.HospitalCode,
        'depArea': this.checkRoomObj.DepArea,
        'dep': this.checkRoomObj.Dep,
        'modalityType': this.checkRoomObj.ModalityType,
        'checkRoom': this.checkRoomObj.CheckRoom,
        // 'modality': '',
        'batchUpdateAppointmentCheckRoomDmbs': []
      }
      // "batchUpdateAppointmentCheckRoomDmbs": [
      //     {
      //       "id": 0,
      //       "week": "string",
      //       "checkClass": "string",
      //       "beginTime": "string",
      //       "endTime": "string",
      //       "initialNum": 0,
      //       "checkNum": 0,
      //       "reserveNum": 0,
      //       "addNum": 0,
      //       "status": "string",
      //       "remark1": "string",
      //       "remark2": "string",
      //       "color": "string",
      //       "appointmentFilters": [
      //         {
      //           "parametersType": "string",
      //           "parametersValues": "string",
      //           "parametersName": "string"
      //         }
      //       ]
      //     }
      //   ]
      // 获取排班模板组件内的 排班数据
      const _scheduledata = JSON.parse(JSON.stringify(this.$refs.fullschedule.scheduledata))
      // // // // console.log('_scheduledata', _scheduledata)
      _scheduledata.forEach(sched => {
        sched.appointment.forEach(appo => {
          // // // // console.log('appo', appo)
          if (!appo.isAddBox) {
            params.batchUpdateAppointmentCheckRoomDmbs = params.batchUpdateAppointmentCheckRoomDmbs.concat(appo)
            // // // // console.log('params.batchUpdateAppointmentCheckRoomDmbs', params.batchUpdateAppointmentCheckRoomDmbs)
          }
        })
      })
      if (params.batchUpdateAppointmentCheckRoomDmbs.length === 0) {
        this.$message.warning('号源模板数据为空！')
        return
      }
      this.$confirm('确认更新到机房号源模板？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        if (params.batchUpdateAppointmentCheckRoomDmbs.length > 0) {
          params.batchUpdateAppointmentCheckRoomDmbs.forEach(item => {
            // 初始化
            item.status = '启用'
            item.id = 0
          })
          this.loading = true
          postAppTempbatchupdateSend(params, 1).then(res => {
            this.loading = false
            if (res && res.code === 10000) {
              this.$message.success('号源模板更新成功！')
              this.$emit('updateTemplateSuccesss')
            }
          })
        }
      }).catch(() => {})
    },
    // 关闭模态框
    dlgClose() {
      this.isShowAppoReleaseInfo && this.$refs.appoReleaseInfo.close()
      this.isShowScheduleTemplateForm && this.$refs.scheduleTemplateForm.close()
    },
    // 号源出错显示
    openSelectedView() {
      this.isShowAppoErrorList = true
      this.$nextTick(() => {
        this.$refs.appoErrorList.show()
      })
    },
    // 号源出错显示
    appoErrorEidt() {
      this.$refs.appoErrorList.show()
    },
    errorChange(data) {
      this.appoErrorListData = [...data]
      this.$refs.fullschedule.isChanged = true
    },
    // 打开显示时间出错的时段号源列表
    appoErrorListChange(data) {
      this.appoErrorListData = data ? [...data] : this.appoErrorListData
      this.$refs.appoErrorList.init(JSON.parse(JSON.stringify(this.appoErrorListData)))
    },
    openMoreEidt(data) {
      this.isShowApproSelectedView = true
      this.$nextTick(() => {
        let weeks = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日']
        if (data.type == 'edit_in') {
          let number = weeks.indexOf(data.row.week)
          const schedule = JSON.parse(JSON.stringify(this.$refs.fullschedule.scheduledata))
          this.$refs.selectedViewRef.open([schedule[number]] || [])
        } else {
          if (this.checkedAppoData.length == 1) {
            let number = weeks.indexOf(this.checkedAppoData[0].week || data.row.week)
            const schedule = JSON.parse(JSON.stringify(this.$refs.fullschedule.scheduledata))
            this.$refs.selectedViewRef.open([schedule[number]] || [])
          } else {
            this.$message.warning('仅支持选择一天的号源进行修改')
          }
        }
      })
    },
    // 出错时段号源，处理完后回传周模板
    errorInsert(data) {
      // // console.log(data)
      this.$refs.fullschedule.insertError(data)
    }
  }
}
</script>

<style lang="scss" scoped>
.appo-header{
  display: flex;
  justify-content: space-between;
  align-items: center;
  .ope_btns{
    text-align: right;
    /deep/ .el-button{
      margin: 5.3333px 0;
    }
  }
}
.item-line-36 /deep/ .el-form-item__content{
  line-height: 36px;
}
</style>
